#!/bin/bash
# Docker统一管理脚本

set -e  # 遇到错误立即退出

echo "🐳 边缘云端AI训练系统 - Docker管理工具"
echo "========================================"
echo ""

# 检查Docker是否运行
if ! docker info >/dev/null 2>&1; then
    echo "❌ Docker未运行或无法访问，请检查Docker服务状态"
    exit 1
fi

# 显示菜单
show_menu() {
    echo "请选择操作:"
    echo ""
    echo "📦 镜像管理:"
    echo "  1) 构建镜像"
    echo "  2) 查看镜像"
    echo ""
    echo "🚀 容器管理:"
    echo "  3) 启动容器"
    echo "  4) 停止容器"
    echo "  5) 重启容器"
    echo "  6) 查看容器状态"
    echo ""
    echo "🔧 运维工具:"
    echo "  7) 查看日志"
    echo "  8) 进入容器"
    echo "  9) 健康检查"
    echo ""
    echo "🧹 清理工具:"
    echo "  10) 清理系统"
    echo ""
    echo "📖 帮助文档:"
    echo "  11) 查看部署文档"
    echo "  12) 显示快速命令"
    echo ""
    echo "  0) 退出"
    echo ""
}

# 容器配置
CONTAINER_NAME="edge-cloud-ai"
IMAGE_NAME="localhost/edge-cloud-ai:latest"

# 检查容器状态
check_container_status() {
    if docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
        echo "✅ 容器正在运行"
        docker ps --filter "name=${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
        return 0
    elif docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
        echo "⏸️  容器已停止"
        docker ps -a --filter "name=${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}"
        return 1
    else
        echo "⚠️  容器不存在"
        return 2
    fi
}

# 检查镜像状态
check_image_status() {
    if docker images --format '{{.Repository}}:{{.Tag}}' | grep -q "${IMAGE_NAME}"; then
        echo "✅ 镜像存在"
        docker images "${IMAGE_NAME%:*}" --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"
        return 0
    else
        echo "⚠️  镜像不存在"
        return 1
    fi
}

# 主循环
main() {
    while true; do
        clear
        echo "🐳 边缘云端AI训练系统 - Docker管理工具"
        echo "========================================"
        echo ""
        
        # 显示当前状态
        echo "📊 当前状态:"
        check_image_status >/dev/null 2>&1 && echo "  镜像: ✅ 已构建" || echo "  镜像: ❌ 未构建"
        check_container_status >/dev/null 2>&1 && echo "  容器: ✅ 运行中" || echo "  容器: ⏸️  已停止/不存在"
        echo ""
        
        show_menu
        
        read -p "请输入选项 (0-12): " -n 2 -r
        echo
        echo ""
        
        case $REPLY in
            1)
                echo "🔨 构建镜像..."
                ./docker-build.sh
                read -p "按任意键继续..."
                ;;
            2)
                echo "📋 查看镜像..."
                check_image_status
                echo ""
                docker images | grep -E "(REPOSITORY|edge-cloud)" || echo "没有找到相关镜像"
                read -p "按任意键继续..."
                ;;
            3)
                echo "🚀 启动容器..."
                if check_container_status >/dev/null 2>&1; then
                    echo "容器已在运行中"
                else
                    read -p "请输入端口 (默认8000): " port
                    port=${port:-8000}
                    ./docker-run.sh $port
                fi
                read -p "按任意键继续..."
                ;;
            4)
                echo "🛑 停止容器..."
                ./docker-stop.sh
                read -p "按任意键继续..."
                ;;
            5)
                echo "🔄 重启容器..."
                if check_container_status >/dev/null 2>&1; then
                    docker restart "${CONTAINER_NAME}"
                    echo "✅ 容器已重启"
                else
                    echo "❌ 容器未运行，请先启动容器"
                fi
                read -p "按任意键继续..."
                ;;
            6)
                echo "📊 容器状态详情..."
                check_container_status
                if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
                    echo ""
                    echo "详细信息:"
                    docker inspect "${CONTAINER_NAME}" --format '{{json .State}}' | python3 -m json.tool 2>/dev/null || echo "无法解析详细信息"
                fi
                read -p "按任意键继续..."
                ;;
            7)
                echo "📝 查看日志..."
                echo "1) 查看最近日志"
                echo "2) 实时跟踪日志"
                read -p "选择 (1-2): " -n 1 -r
                echo
                if [ "$REPLY" = "1" ]; then
                    ./docker-logs.sh
                else
                    echo "按 Ctrl+C 退出日志跟踪"
                    ./docker-logs.sh -f
                fi
                read -p "按任意键继续..."
                ;;
            8)
                echo "🔧 进入容器..."
                if check_container_status >/dev/null 2>&1; then
                    echo "进入容器shell (输入 exit 退出):"
                    ./docker-exec.sh
                else
                    echo "❌ 容器未运行，无法进入"
                fi
                read -p "按任意键继续..."
                ;;
            9)
                echo "🏥 健康检查..."
                if check_container_status >/dev/null 2>&1; then
                    echo "正在检查服务健康状态..."
                    if curl -f http://localhost:8000/api/v1/health >/dev/null 2>&1; then
                        echo "✅ 服务健康"
                        curl -s http://localhost:8000/api/v1/health | python3 -m json.tool 2>/dev/null || echo "服务响应正常"
                    else
                        echo "❌ 服务不健康或无法访问"
                    fi
                else
                    echo "❌ 容器未运行"
                fi
                read -p "按任意键继续..."
                ;;
            10)
                echo "🧹 系统清理..."
                ./docker-clean.sh
                read -p "按任意键继续..."
                ;;
            11)
                echo "📖 查看部署文档..."
                if [ -f "docker-deploy.md" ]; then
                    less docker-deploy.md
                else
                    echo "❌ 部署文档不存在"
                fi
                read -p "按任意键继续..."
                ;;
            12)
                echo "⚡ 快速命令参考:"
                echo ""
                echo "构建和运行:"
                echo "  ./docker-build.sh && ./docker-run.sh"
                echo ""
                echo "查看状态:"
                echo "  docker ps -a | grep edge-cloud"
                echo ""
                echo "快速重启:"
                echo "  docker restart edge-cloud-ai"
                echo ""
                echo "查看日志:"
                echo "  docker logs -f edge-cloud-ai"
                echo ""
                echo "进入容器:"
                echo "  docker exec -it edge-cloud-ai bash"
                echo ""
                echo "完全重建:"
                echo "  ./docker-clean.sh && ./docker-build.sh && ./docker-run.sh"
                echo ""
                read -p "按任意键继续..."
                ;;
            0)
                echo "👋 再见!"
                exit 0
                ;;
            *)
                echo "❌ 无效选项，请重新选择"
                sleep 2
                ;;
        esac
    done
}

# 检查必要的脚本文件
required_files=("docker-build.sh" "docker-run.sh" "docker-stop.sh" "docker-logs.sh" "docker-exec.sh" "docker-clean.sh")
missing_files=()

for file in "${required_files[@]}"; do
    if [ ! -f "$file" ]; then
        missing_files+=("$file")
    fi
done

if [ ${#missing_files[@]} -ne 0 ]; then
    echo "❌ 缺少必要的脚本文件:"
    printf '  - %s\n' "${missing_files[@]}"
    echo ""
    echo "请确保所有Docker管理脚本都存在于当前目录"
    exit 1
fi

# 启动主程序
main 